import api from './api';

export const aiService = {
    // 生成步骤链 - 同步版本
    generateStepChain: (taskName, requirements) => {
        return api.post('/api/ai/generate-steps', {
            taskName,
            requirements
        });
    },

    // 异步生成步骤链
    generateStepChainAsync: (taskName, requirements) => {
        return api.post('/api/ai/generate-steps-async', {
            taskName,
            requirements
        });
    },

    // 订阅 SSE 事件 - 新增函数
    subscribeToStepEvents: (taskUUID, onMessage, onError) => {
        const eventSource = new EventSource(`/api/ai/events/${taskUUID}`);

        eventSource.onmessage = (event) => {
            const data = JSON.parse(event.data);
            onMessage(data);
        };

        eventSource.onerror = (error) => {
            console.error('SSE 连接错误:', error);
            eventSource.close();
            if (onError) onError(error);
        };

        return eventSource;
    },

    // 获取异步任务状态
    getAsyncTaskStatus: (taskId) => {
        return api.get(`/api/ai/async-task/${taskId}`);
    },

    // 优化步骤链
    optimizeStepChain: (steps, feedback) => {
        return api.post('/api/ai/optimize-steps', {
            steps,
            feedback
        });
    },

    // 调整步骤链
    adjustStepChain: (currentSteps, progressUpdate, challenges) => {
        return api.post('/api/ai/adjust-steps', {
            currentSteps,
            progressUpdate,
            challenges
        });
    }
};
